<template>
  <div class="cart-container">
    <!-- 购物车列表 -->
    <div class="cart-item">
      <span style="width: 60px">图片</span>
      <span style="width: 60px">名称</span>
      <span style="width: 60px">数量</span>
      <span style="width: 60px">单价</span>
      <span style="width: 60px">总价</span>
      <span style="width: 60px">操作</span>
    </div>
    <div
      class="cart-item"
      v-for="(item, index) in cartItems"
      :key="item.cartId"
    >
      <el-image
        class="item-image"
        :src="item.url"
        fit="cover"
        :alt="item.name"
      ></el-image>
      <span style="width: 60px">{{ item.name }}</span>
      <span style="width: 60px">{{ item.count }}</span>
      <span style="width: 60px">{{ item.price }}</span>
      <span style="width: 60px">{{ item.price * item.count }}</span>
      <el-button @click="removeItem(item, index)">删除</el-button>
    </div>
    <!-- 操作区 -->
    <div class="cart-operations">
      <el-button type="primary" @click="go">结算</el-button>
      <span>选中商品总数：{{ selectedCount }}</span>
      <span>选中商品总价：{{ selectedTotalPrice }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import * as cartapi from "@/api/cart";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const store = useStore();
const cartItems = ref([]);
const getcarts = async () => {
  const { data } = await cartapi.getAllList({
    userId: store.state.userInfo.userId,
  });
  cartItems.value = data;
};
getcarts();

// 删除单个商品
function removeItem(item, index) {
  cartapi.delItem({ cartId: item.cartId });
  cartItems.value.splice(index, 1);
  ElMessage.success("删除成功");
}

// 计算属性：选中商品的总价和总数
const selectedTotalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.price * item.count;
  }, 0);
});

const selectedCount = computed(() => {
  return cartItems.value.length;
});
const go = () => {
  router.push("/user/order");
};
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.cart-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.cart-item:last-child {
  border-bottom: none;
}

.cart-item span {
}

.cart-operations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
}

.cart-operations .el-button {
  margin-right: 10px;
}

.cart-operations span {
  font-size: 16px;
}

/* 调整按钮样式 */
.el-button {
  margin-left: 10px;
}
.item-image {
  width: 60px;
  height: 60px;
  margin-right: 15px;
  object-fit: cover;
}
</style>